package com.isoft.service.impl;

import com.isoft.entity.DfmeStlsEntity;
import com.isoft.mapper.DfmeStlsMapper;
import com.isoft.service.DfmeStlsService;
import com.isoft.util.XmlParserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Service
public class DfmeStlsServiceImpl implements DfmeStlsService {
    private static final Logger logger = LoggerFactory.getLogger(DfmeStlsServiceImpl.class);

    @Autowired
    private DfmeStlsMapper dfmeStlsMapper;

    @Autowired
    private XmlParserUtil xmlParserUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(MultipartFile file) throws IOException {
        try {
            String xmlContent = new String(file.getBytes(), StandardCharsets.UTF_8);
            logger.info("Processing XML file: {}, size: {} bytes",
                    file.getOriginalFilename(), file.getSize());
            return parseAndSave(xmlContent);
        } catch (Exception e) {
            logger.error("File processing failed", e);
            throw new IOException("Failed to process file: " + e.getMessage(), e);
        }
    }

    @Override
    public void parseAndSave(DfmeStlsEntity entity) {
        processFlightData(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(String xmlContent) {
        try {
            if (xmlContent == null || xmlContent.trim().isEmpty()) {
                throw new IllegalArgumentException("XML content cannot be null or empty");
            }

            logger.debug("Original XML content: {}", xmlContent.substring(0, Math.min(200, xmlContent.length())));

            DfmeStlsEntity entity = xmlParserUtil.parseXml(xmlContent, DfmeStlsEntity.class);
            if (entity == null) {
                throw new IllegalArgumentException("Parsed entity is null");
            }
            if (entity.getDflt() == null) {
                throw new IllegalArgumentException("DFLT section is missing in XML");
            }

            // 验证必填字段
            validateRequiredFields(entity);

            processFlightData(entity);

            return "Flight stand data processed successfully. Flight ID: " + entity.getDflt().getFlightId();
        } catch (Exception e) {
            logger.error("XML processing failed", e);
            throw new RuntimeException("Failed to process XML: " + e.getMessage(), e);
        }
    }

    private void validateRequiredFields(DfmeStlsEntity entity) {
        if (entity.getDflt().getStls() == null || entity.getDflt().getStls().getStnd() == null) {
            throw new IllegalArgumentException("STLS/STND section is missing in XML");
        }

        if (entity.getDflt().getStls().getStnd().getStandNumber() == null) {
            throw new IllegalArgumentException("STNO (Stand Number) is required");
        }

        if (entity.getDflt().getStls().getStnd().getCode() == null ||
                entity.getDflt().getStls().getStnd().getCode().isEmpty()) {
            throw new IllegalArgumentException("CODE is required");
        }
    }

    private void processFlightData(DfmeStlsEntity entity) {
        // 插入元数据
        dfmeStlsMapper.insertMeta(entity);

        // 插入航班基础信息
        dfmeStlsMapper.insertFlightBase(entity);

        // 插入行李转盘信息
        if (entity.getDflt().getStls() != null && entity.getDflt().getStls().getStnd() != null) {
            dfmeStlsMapper.insertBaggageClaim(entity);
        }
    }
}